using BackOffice.Application.DTOs;
using BackOffice.Application.Services;
using Microsoft.AspNetCore.Http;

namespace BackOffice.Application.Common;

public static class LogHelper
{
    public static async Task LogInfoAsync(ILogService logService, HttpContext context, string action, string description = "")
    {
        await LogAsync(logService, context, action, description, "INFO");
    }

    public static async Task LogWarningAsync(ILogService logService, HttpContext context, string action, string description = "")
    {
        await LogAsync(logService, context, action, description, "WARNING");
    }

    public static async Task LogErrorAsync(ILogService logService, HttpContext context, string action, string description = "")
    {
        await LogAsync(logService, context, action, description, "ERROR");
    }

    public static async Task LogDebugAsync(ILogService logService, HttpContext context, string action, string description = "")
    {
        await LogAsync(logService, context, action, description, "DEBUG");
    }

    private static async Task LogAsync(ILogService logService, HttpContext context, string action, string description, string level)
    {
        try
        {
            var username = context.User?.Identity?.Name ?? "anonymous";
            var ipAddress = GetClientIpAddress(context);
            var userAgent = context.Request.Headers["User-Agent"].ToString();
            var sessionId = context.Session?.Id ?? "";

            var logDto = new LogRecordDto(
                Username: username,
                Action: $"[{level}] {action}",
                Description: description,
                IpAddress: ipAddress,
                UserAgent: userAgent,
                Level: level,
                SessionId: sessionId
            );

            await logService.RecordLogAsync(logDto);
        }
        catch (Exception ex)
        {
            // 避免日志记录失败影响主流程
            Console.WriteLine($"日志记录失败: {ex.Message}");
        }
    }

    private static string GetClientIpAddress(HttpContext context)
    {
        var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
        }
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Connection.RemoteIpAddress?.ToString();
        }
        return ip ?? "unknown";
    }
} 